<?php
/**
 * Author: xx.com
 */ 
namespace Shop\Controller;
use Think\Controller;
use Think\Page;
use Common\Util\JuheSms;

class UserController extends BaseController {
    public $userLogic;
    
    /**
     * 析构流函数
     */
    public function  __construct() {   
        parent::__construct();    
        //$this->userLogic = new \Home\Logic\UsersLogic();
    }

    public function index(){
        $this->userInfo();
    }
   
    /**
     *  登录
     */
    public function login(){
        $username = I('username','', 'trim');
        //$password = I('password','');
        $code = I('code', '', 'trim');
        $unique_id = I("unique_id"); // 唯一id  类似于 pc 端的session id

        if(!$username || !code){
            $result= array('status'=>0,'msg'=>'请填写账号或短信验证码', 'result'=>'');
            exit(json_encode($result));
        }
        $field = array('admin_id', 'user_name', 'password', 'token', 'user_id');
        $user = M('admin')->field($field)->where(array('user_name'=>$username, 'role_id'=>8))->find();
        if(!$user){
            $this->returnInfo(-1, '账号不存在');
        }elseif($user['disabled'] == 1){
            $this->returnInfo(-1, '账号异常已被锁定！！！');
        }else{
            $sms = M('sms')->where(array('mobile'=>$username, 'code'=>$code, 'times'=>0, 'event'=>'shop_login'))->order('id DESC')->find();
            if(!$sms){
                $this->returnInfo(-1, '未发送短信验证码');
            }
            //短信验证码过期时间
            $sms_time_out = tpCache('sms.sms_time_out')?tpCache('sms.sms_time_out') : 300;
            $out_time = time() - $sms_time_out;
            if($out_time > $sms['createtime']){
                M('sms')->where(array('id'=>$sms['id']))->setField('times', 1);
                $this->returnInfo(-1, '短信验证码已过期，请重新发送!！！！');
            }
            //商家信息
            $user['token'] = md5(time().mt_rand(1,999999999));
            M('admin')->where("admin_id = {$user['admin_id']}")->save(array('token'=>$user['token'],'last_login'=>time()));
            //验证码使用状态
            M('sms')->where(array('id'=>$sms['id']))->setField('times', 1);

            unset($user['admin_id']);
            unset($user['password']);
            $field_shop = array('id as shop_id', 'shop_name', 'shop_user', 'shop_tel', 'shop_status', 'isvalid', 'goods_type', 'is_open'
                , 'shop_intro', 'shop_address_city', 'shop_address_street', 'longitude', 'latitude','wallet_balance', 'money_amount',
                'shop_head_img', 'is_auto_confirm');
            $shop_info = M('shop')->field($field_shop)->where(array('user_id'=>$user['user_id']))->find();
            $shop_info['shop_head_img'] = parseMediaUrl($shop_info['shop_head_img']);
            $renturn_data['token'] = $user['token'];
            $renturn_data['shop_info'] = $shop_info;

            $this->returnInfo(1, '登陆成功', $renturn_data);
        }
    }

    /*
     * 获取用户信息
     */
    public function shopInfo(){
        $shop_info = $this->shop_info;
        $with_shop_period = tpCache('basic.with_shop_period');
        $with_shop_period_data = tpCache('basic.with_shop_period_data');
        $shop_info['with_shop_period'] = $with_shop_period;
        $shop_info['with_shop_period_data'] = $with_shop_period_data;
        $data = array('status'=>1,'msg'=>'获取成功','result'=>$shop_info);
        exit(json_encode($data));
    }
    /*
     * 发送短信验证码
     */
    public function send_sms_code(){
        $mobile = I('mobile');
        $unique_id = I('unique_id');
        if(!check_mobile($mobile))
            $this->returnInfo(-1, '手机号码格式有误');
        //账号状态
        $field = array('admin_id', 'user_name', 'password', 'token');
        $user = M('admin')->field($field)->where("user_name='{$mobile}'")->find();
        if(!$user){
            $this->returnInfo(-1, '账号不存在!');
        }elseif($user['disabled'] == 1){
            $this->returnInfo(-1, '账号异常已被锁定！！！!');
        }

        $sms = M('sms')->where(array('mobile'=>$mobile, 'times'=>0, 'event'=>'shop_login'))->order('id DESC')->find();
        if($sms){
            $sms_time_out = tpCache('sms.sms_time_out')?tpCache('sms.sms_time_out') : 300;
            $out_time = time() - $sms_time_out;
            if($out_time > $sms['createtime']){
                M('sms')->where(array('id'=>$sms['id']))->setField('times', 1);
            }else{
                $this->returnInfo(-1, '短信验证码已发送，请勿重复发送!！！！');
            }
        }

        //失效时间内存在未使用短信验证码
        //$code =  rand(1000,9999);
        $code = 1234;
        //验证是否已经注册

        //$send = $this->userLogic->sms_log($mobile,$code,$unique_id);
        $send_data['mobile'] = $mobile;
        $send_data['code'] = $code;

        $juhesms = new JuheSms();
        //$send = $juhesms->smsSend($send_data);
        $send = true;//
        if(!$send){
            $this->returnInfo(-1, $send['msg']);
        }
        $send_data['event'] = 'shop_login';
        $send_data['createtime'] = time();
        M('sms')->add($send_data);
        $this->returnInfo(1, '验证码已发送，请注意查收');
    }

    /**
     * 销售数据
     */
    public function sale_data(){
        $start_time = I('start_time', '', 'trim');
        $end_time = I('end_time', '', 'trim');

        if($start_time){
            $start_time = strtotime($start_time);
        }

        if($end_time){
            $end_time .= ' 23:59:59';
            $end_time = strtotime($end_time);
            if($end_time < $start_time){
                $this->returnInfo(-1, '结束时间不能大于开始时间');
            }
        }

        $where['shop_id'] = $this->shop_info['shop_id'];
        $where_plat['shop_id'] = $this->shop_info['shop_id'];
        if($start_time > 0 && $end_time > 0){
            $where['add_time'] = array(array('gt', $start_time), array('lt', $end_time));
            $where_plat['create_time'] = array('between', array($start_time, $end_time));
        }else if($start_time > 0){
            //$where['add_time'] = array('gt', $start_time);
            $end_time = $start_time + 24 * 3600;
            $where['add_time'] = array('between', array($start_time, $end_time));
            $where_plat['create_time'] = array('between', array($start_time, $end_time));
        }else if($end_time > 0){
            $where['add_time'] = array('lt', $end_time);
            $where_plat['create_time'] = array('lt', $end_time);
        }
        $orderModel = M('order');
        //订单数量
        $order_num = $orderModel->where($where)->count();
        //销售额
        $order_amount = 0;
        if($order_num > 0){
            $order_amount = $orderModel->where($where)->sum('order_amount');
        }
        //平台扣除

        $field[] = 'SUM(service_money) as service_amount';
        $field[] = 'SUM(exp_money_shop) as exp_shop_amount';
        $platform_data = M('shop_capital_log')->field($field)->where($where_plat)->find();

        $return_data['order_num'] = $order_num;
        $return_data['order_amount'] = $order_amount;
        $return_data['platform_cost'] = $platform_data['service_amount'] ? $platform_data['service_amount'] : 0;
        $return_data['exp_cost'] = $platform_data['exp_shop_amount'] ? $platform_data['exp_shop_amount'] : 0;
        $this->returnInfo(1, '销售数据', $return_data);
    }

    /**
     * 设置店铺数据
     */
    public function set_options(){

        $is_open = I('is_open', 0, 'intval');   //营业状态
        $shop_name = I('shop_name', '', 'trim');
        $shop_user = I('shop_user', '', 'trim');
        $shop_tel = I('shop_tel', '', 'trim');
        $shop_intro = I('shop_intro', '', 'trim');
        $is_auto_confirm = I('is_auto_confirm', 0, 'intval');
        $shop_head_img = I('shop_head_img');
        $city_name = I('city_name', '', 'trim');    //dada城市名
        $area_name = I('area_name', '', 'trim');    //达达区域名
        $city_code = I('city_code', '', 'trim');    //dada城市编号

        $update_data = array();

        $fields = array('is_open', 'shop_name', 'shop_user', 'shop_tel', 'shop_intro', 'is_auto_confirm', 'city_code', 'city_name', 'area_name');
        $where['id'] = $this->shop_info['shop_id'];
        $shopModel = M('shop');
        $shop_info = $shopModel->where($where)->field($fields)->find();

        if($is_open == 1){
            $update_data['is_open'] = $shop_info['is_open'] == 0 ? 1 : 0;
        }

        if($shop_name && $shop_name != $shop_info['shop_name']){
            $has_shop = $shopModel->where(array('shop_name'=>$shop_name, 'id'=>array('neq',  $this->shop_info['shop_id'])))->count();
            if($has_shop > 0){
                $this->returnInfo(-1, '店铺名称已被使用');
            }
            $update_data['shop_name'] = $shop_name;
        }

        if($shop_tel && $shop_tel != $shop_info['shop_tel']){
            $has_shop = $shopModel->where(array('shop_tel'=>$shop_tel, 'id'=>array('neq',  $this->shop_info['shop_id'])))->count();
            if($has_shop > 0){
                $this->returnInfo(-1, '联系电话已被使用');
            }
            $update_data['shop_tel'] = $shop_tel;
        }

        if($shop_user && $shop_user != $shop_info['shop_user']){
            $update_data['shop_user'] = $shop_user;
        }

        if($shop_intro && $shop_intro != $shop_info['shop_intro']){
            $update_data['shop_intro'] = $shop_intro;
        }

        if($is_auto_confirm == 1){
            $update_data['is_auto_confirm'] = $shop_info['is_auto_confirm'] == 0 ? 1 : 0;
        }

        if($city_name && $city_name != $shop_info['city_name']){
            $update_data['city_name'] = $city_name;
        }

        if($area_name && $area_name != $shop_info['area_name']){
            $update_data['area_name'] = $area_name;
        }

        if($city_code && $city_code != $shop_info['city_code']){
            $update_data['city_code'] = $city_code;
        }


        if($shop_head_img){
            $update_data['shop_head_img'] = $shop_head_img;
        }

        if($update_data){
            $is_success = $shopModel->where($where)->save($update_data);
            if($is_success === false){
                $this->returnInfo(-1, '操作失败');
            }
            $this->returnInfo(1, '操作成功');
        }
        $this->returnInfo(-1, '无更新数据');
    }

    /**
     * base64图片上传
     * @param $base64_img
     * @return array
     */
    public function open_base64_img_upload(){
        $base64_img = I('base64_img');
        $upload_route = I('upload_route');
        $upload_route_list = C('FILE_BASE_UPLOAD_ROUTE');
        if(!$upload_route_list[$upload_route]){
            $this->returnInfo('-1', '不可用上传路径');
        }
        $upload_object = $this->base64_img_upload($base64_img,$upload_route_list[$upload_route]);
        if($upload_object['status'] == 1){
            $this->returnInfo('1', '图片上传成功',['img_path' => $upload_object['url'],'images_url' => parseMediaUrl($upload_object['url'])]);
        }else{
            $this->returnInfo('-1', $upload_object['msg']);
        }

    }

    /**
     * base64图片上传
     * @param $base64_img
     * @return array
     */
    private static function base64_img_upload($base64_img,$upload_route){
        $base64_img = trim($base64_img);
        $time = time();
        $date = date('Y');
        $date1 = date('m-d');
        // $up_dir = './Public/upload/head_pic/'.$date.'/'.$date1.'/';
        $up_dir = $upload_route.$date.'/'.$date1.'/';
        if(!file_exists($up_dir)){
            mkdir($up_dir,0777,true);
        }
        if(preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_img, $result)){
            $type = $result[2];
            if(in_array($type,array('pjpeg','jpeg','jpg','gif','bmp','png'))){
                $new_file = $up_dir.$time.'.'.$type;
                //var_dump($new_file);exit;
                if(file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_img)))){
                    $img_path = str_replace('./', '/', $new_file);
                    return array('status' => 1, 'msg' => "图片上传成功", 'url' => $img_path);
                }
                return array('status' => 2, 'msg' => "图片上传失败");
            }
            //文件类型错误
            return array('status' => 4, 'msg' => "文件类型错误");
        }
        //文件错误
        return array('status' => 3, 'msg' => "文件错误");
    }

    /**
     * 商家意见反馈
     */
    public function shop_feedback(){
        $adddata['shop_id'] = $this->shop_info['shop_id'];
        $adddata['content'] = I('content', '', 'trim');
        $adddata['add_time'] = time();

        $urlpath = I("urlpath");
        if(is_array ($urlpath))
        {
            $upload_route = './Public/upload/drawback/';
            foreach($urlpath as $k => $v){
                $return = $this->base64_img_upload($v,$upload_route);
                if($return['status'] == 1){
                    $drawback_img[] = $return['url'];
                }
            }
            $adddata['img'] = serialize($drawback_img);// 上传的图片文件
        }
        $id = M('feedback_shop')->add($adddata);
        if($id){
            $this->returnInfo(1, '操作成功');
        }else{
            $this->returnInfo(1, '操作失败');
        }
    }

    /**
     * 账户明细列表
     */
    public function account_log(){
        $p = I('p', 1, 'intval');
        $pagesize = I('pagesize', 10, 'intval');
        $accountLogShop = M('account_log_shop');
        $where['shop_id'] = $this->shop_info['shop_id'];
        $count =  $accountLogShop->where($where)->count();
        $list = $accountLogShop
            ->where($where)
            ->order('change_time DESC')
            ->page($p, $pagesize)
            ->select();
        foreach($list as &$val){
            $val['change_time'] = date('Y-m-d H:i');
        }

        $page_info = array('count'=>$count, 'page_count'=>count($list), 'p'=>I('p',1,'intval'), 'page_size'=>$pagesize);
        $this->returnInfo(1, '账户明细列表',  array('page_info'=>$page_info, 'list'=>$list));
    }

    /**
     * 店铺账号列表
     */
    public function shop_settlement_card(){
        $list = M('shop_settlement_card')->where(array('shop_id'=>$this->shop_info['shop_id']))->select();
        $this->returnInfo(1, '店铺银行账号列表', $list);
    }

    /**
     * 店铺申请提现
     */
    public function shop_withdrawals(){
        //$card_id = I('card_id', 0, 'intval');
        //$card_info = M('shop_settlement_card')->where(array('shop_id'=>$this->shop_info['shop_id'], 'id'=>$card_id))->find();
        //if(!$card_info){
        //    $this->returnInfo(0, '提现账户有误');
        //}

        $with_shop_period = tpCache('basic.with_shop_period');
        $with_shop_period_data = tpCache('basic.with_shop_period_data');
        $with_shop_period_data = explode(',', $with_shop_period_data);
        if($with_shop_period == 1){
            $week_data = date('w');
            if($week_data == 0){
                $week_data = 7;
            }
            if(!in_array($week_data, $with_shop_period_data)){
                $this->returnInfo(0, '请在规定日期申请提现');
            }
        }else if($with_shop_period == 2){
            $month_data = date('d');
            if(!in_array($month_data, $with_shop_period_data)){
                $this->returnInfo(0, '请在规定日期申请提现');
            }
        }

        $money = I('money', 0, 'floatval');
        if($money <= 0){
            $this->returnInfo(0, '提现金额有误');
        }
        $shop_info = M('shop')->field('wallet_balance, user_id')->where(array('id'=>$this->shop_info['shop_id']))->find();
        $wallet_balance = $shop_info['wallet_balance'];
        if($money > $wallet_balance){
            $this->returnInfo(0, '钱包余额不足');
        }
        $add_data['shop_id'] = $this->shop_info['shop_id'];
        $add_data['create_time'] = time();
        $add_data['money'] = $money;
        //$add_data['bank_name'] = $card_info['card_name'];
        //$add_data['account_bank'] = $card_info['card_number'];
        //$add_data['account_name'] = $card_info['account_name'];
        $add_data['partner_trade_no'] = 'With'.get_rand_str(6,1,1);
        $add_data['user_id'] = $shop_info['user_id'];
        $withdraw_id = M('withdrawals_shop')->add($add_data);

        if(!$withdraw_id){
            M()->rollback();
            $this->returnInfo(0, '操作失败');
        }

        $this->returnInfo(1, '操作成功', $withdraw_id);
    }

    /**
     * 消息列表
     */
    public function message_list(){
        $shop_id = $this->shop_info['shop_id'];
        $p = I('p', 1, 'intval');
        $pagesize = I('pagesize', 10, 'intval');
        $where['shop_id'] = $shop_id;
        $messageModel = M('message_shop');
        $count =  $messageModel->where($where)->count();
        $fields = array('id','title', 'message', 'type', 'send_time', 'status', 'rele_id');

        $list = $messageModel
            ->field($fields)
            ->where($where)
            ->order('send_time DESC')
            ->page($p, $pagesize)
            ->select();
        foreach($list as &$val){
            $val['send_time'] = date('Y-m-d H:i');
        }

        $page_info = array('count'=>$count, 'page_count'=>count($list), 'p'=>I('p',1,'intval'), 'page_size'=>$pagesize);
        $this->returnInfo(1, '消息列表',  array('page_info'=>$page_info, 'list'=>$list));
    }

    /**
     * 修改消息状态
     */
    public function update_message_status(){
        $id = I('id', 0, 'intval');
        $is_success = M('message_shop')->where(array('id'=>$id))->setField('status', 1);
        if($is_success === false){
            $this->returnInfo(0, '操作失败');
        }
        $this->returnInfo(1, '操作成功');
    }

    /**
     * 需要补货数据提示
     */
    public function need_repl(){
        //需要补货
        $where = array(
            'shop_id'=>$this->shop_info['shop_id'],
            'shop_on_sale' =>1,
        );
        $field = array('id', 'store_count');
        $shop_goods = $shop_goods = M('shop_goods')
            ->field($field)
            ->where($where)
            ->select();
        $need_repl = tpCache('basic.warning_storage');
        $need_repl_count = 0;
        //$shop_goods_id = array();
        foreach($shop_goods as $val){
            if($val['store_count'] <= $need_repl){
                $need_repl_count++;
                //$shop_goods_id[] = $val['id'];
            }
        }

        $this->returnInfo(1, '补货数据', array('need_repl_count'=>$need_repl_count));
    }

    /**
     * 店铺账号列表
     */
    public function edit_settlement_card(){
        $id = I('id', 0, 'intval');
        $cardModel = M('shop_settlement_card');
        if($id){
            $card_info = $cardModel->where(array('shop_id'=>$this->shop_info['shop_id'], 'id'=>$id))->find();
            if(!$card_info){
                $this->returnInfo(0, '账号信息有误');
            }
            $card_type = I('card_type', -1, 'intval');
            if(!in_array($card_type, array(0, 1, 2))){
                $this->returnInfo(0, '账号类型有误');
            }
            $mobile = I('mobile', '', 'trim');
            if(!check_mobile($mobile)){
                $this->returnInfo(0, '手机号码有误');
            }

            $update_data['card_type'] = $card_type;
            $update_data['card_name'] = I('card_name', '', 'trim');
            $update_data['card_number'] = I('card_name', '', 'trim');
            $update_data['update_time'] = time();
            $update_data['isvalid'] = 1;
            $update_data['bank_address'] = I('card_name', '', 'trim');
            $update_data['account_name'] = I('card_name', '', 'trim');
            $update_data['mobile'] = $mobile;

            $cardModel->where(array('id'=>$id))->save($update_data);

        }else{
            $card_type = I('card_type', -1, 'intval');
            if(!in_array($card_type, array(0, 1, 2))){
                $this->returnInfo(0, '账号类型有误');
            }
            $mobile = I('mobile', '', 'trim');
            if(!check_mobile($mobile)){
                $this->returnInfo(0, '手机号码有误');
            }
            $add_data['shop_id'] = $this->shop_info['shop_id'];
            $add_data['card_type'] = $card_type;
            $add_data['card_name'] = I('card_name', '', 'trim');
            $add_data['card_number'] = I('card_name', '', 'trim');
            $add_data['create_time'] = time();
            $add_data['isvalid'] = 1;
            $add_data['bank_address'] = I('card_name', '', 'trim');
            $add_data['account_name'] = I('card_name', '', 'trim');
            $add_data['mobile'] = $mobile;

            $id = $cardModel->add($add_data);

        }
        $card_info = $cardModel->where(array('id'=>$id))->find();
        $this->returnInfo(1, '操作成功', $card_info);
    }
    /*
     * 删除提现账户
     */
    public function del_settlement_card(){
        $id = I('id', 0, 'intval');
        $cardModel = M('shop_settlement_card');
        $card_info = $cardModel->where(array('shop_id'=>$this->shop_info['shop_id'], 'id'=>$id))->find();
        if(!$card_info){
            $this->returnInfo(0, '账号信息有误');
        }
        $is_success = $cardModel->where(array('id'=>$id))->delete();
        if($is_success === false){
            $this->returnInfo(0, '操作失败');
        }
        $this->returnInfo(1, '操作成功');

    }

    /**
     * 店铺申请提现
     */
    public function shop_withdrawals_list(){
        $shop_id = $this->shop_info['shop_id'];
        $p = I('p', 1, 'intval');
        $pagesize = I('pagesize', 10, 'intval');
        $where['shop_id'] = $shop_id;

        $withdrawModel = M('withdrawals_shop');

        $count =  $withdrawModel->where($where)->count();
        $list = $withdrawModel->where(array('shop_id'=>$shop_id))->page($p, $pagesize)->order('create_time DESC')->select();

        foreach($list as &$val){
            $val['status_show'] = shop_with_status($val['status']);
            $val['create_time'] = date('Y-m-d H:i', $val['create_time']);
            if($val['update_time'])
                $val['update_time'] = date('Y-m-d H:i', $val['update_time']);
        }

        $page_info = array('count'=>$count, 'page_count'=>count($list), 'p'=>I('p',1,'intval'), 'page_size'=>$pagesize);
        $this->returnInfo(1, '提现申请列表',  array('page_info'=>$page_info, 'list'=>$list));
    }
}